package com.yangyouli.unity_demo_server.controller;

import java.util.Timer;

import com.alibaba.fastjson.JSONObject;
import com.yangyouli.unity_demo_server.annotation.ResponseClass;
import com.yangyouli.unity_demo_server.annotation.ResponseMethod;
import com.yangyouli.unity_demo_server.server.RoomObj;
import com.yangyouli.unity_demo_server.server.serializeModel.StopPauseData;
import com.yangyouli.unity_demo_server.util.ThreadLocalHelper;

@ResponseClass("story")
public class StoryController {
	Timer timer = new Timer();
	
	@ResponseMethod("getSection")
	public String getSection(String data) {
		int section = ThreadLocalHelper.getClient().getRoomObj().getSection();
		ThreadLocalHelper.getClient().getRoomObj().setSection(section + 1);
		return "" + (section + 1);
	}
	
	@ResponseMethod("pause")
	public String pause(String data) {
		RoomObj roomObj = ThreadLocalHelper.getClient().getRoomObj();
		roomObj.setPause(true);
		return "" + (roomObj.getClients() != null ? roomObj.getClients().size() + 1 : 1);
	}
	
	@ResponseMethod("stopPause")
	public String stopPause(String data) {
		RoomObj roomObj = ThreadLocalHelper.getClient().getRoomObj();
		int readyNum = roomObj.getReadyPeopleNum();
		roomObj.setReadyPeopleNum(++readyNum);
		int totalNum = roomObj.getClients() != null ? roomObj.getClients().size() + 1 : 1;
		roomObj.setLastStopPauseTime(System.currentTimeMillis());
		StopPauseData stopPauseData = new StopPauseData(readyNum, totalNum, roomObj.getSection(), roomObj.isPause());
		if (roomObj.isPause() && readyNum >= totalNum) {
			roomObj.setPause(false);
			roomObj.setReadyPeopleNum(0);
		} else {
			timer.schedule(roomObj.new StopPauseTask(), RoomObj.MAX_WAIT_STOP_PAUSE_TIME);
		}
		
		return JSONObject.toJSONString(stopPauseData);
	}
}
